var defaultSetting = {
    filtTypes: [
        8201, 8202, 8193, 8193, 4, 32, 64, 8207, 8209
        , 8211, 8213, 8215, 8204, 8203, 8194, 8, 16, 128, 8208, 8210, 8212,
        8214, 8216
    ],
    focusList: [],
    subscribeFilter: {
        inheritAllfil: "0",
        maxRise20Days: '',
        LPrice20Days: '',
        HPrice20Days: '',
    },
    stockType: 'xueqiu'
}
//  配置属性
var allDatafiltTypes = [];
var subscribeFilter = {};
var stockType = "";
var focusCodeArr = [            // 关注的stock Code
    // "603212",                   // 赛伍技术
    // "000911",                   // 南宁糖业
    // "300343",                   // 联创股份
    // "002081",                   // 金螳螂
    // "600518",                   // 康美
    // "600737",                   // 中粮糖业
    // "300376",                   // 易事特
    // "300319",                   // 麦捷科技
    // "002127",                   // 南极电商
    // "000603",                   // 盛达资源
    // "000027",                   // 深圳能源
    // "002228",                   // 合兴包装
    // "002739",                   // 万达电影
    // "600139",                   // 西部资源
    // "000338",                   // 潍柴动力
    // "600699",                   // 均胜电子
    // "002375",                   // 亚夏股份
    // "600496",                   // 精工钢构
    // "000802"                    // 北京文化
]
var followCodeArr = [];               // 自选股票 stock code

// 数据
var allData = [];               //  所有数据
var allFilData = [];            //  依据需求过滤的数据
var subscribeFilData = [];      //  订阅数据
var focusData = [];             //  关注股票的数据
var followData = [];            //  自选股票的数据

var allReaded = {}              //  已读
var censusData = {}             //  统计数据

function getSetting() {
    var settingCfg = localStorage.getItem("unusualSetting")
    return (settingCfg) ? JSON.parse(settingCfg) : defaultSetting;
}
function InitSetting() {
    var setting = getSetting();
    allDatafiltTypes = setting.filtTypes.map(function (item) { return parseInt(item) });
    subscribeFilter = (setting.subscribeFilter) ? setting.subscribeFilter : defaultSetting.subscribeFilter;
    focusCodeArr = setting.focusList.map(function (item) { return item.stockCode });
    followCodeArr = setting.focusList.filter(function (item) { return item.focusType == 2 }).map(function (item) { return item.stockCode });
    // console.log("followCodeArr", followCodeArr , setting.focusList.filter( function(item){ return item.focusType==2 }) )
    stockType = setting.stockType
    // console.log("InitSetting",setting)
    // console.log("focusCodeArr",setting);
}
// 完成配置更新
function emitUpateSetting() {
    InitSetting();
    restartInterval()
}
function getAllData() {
    return allData
}
function setAllData(arr) {
    allData = arr;
}
function getFocusData() {
    return focusData
}
function setFocusData(arr) {
    focusData = arr;
}
function getAllReaded() {
    return allReaded
}
function setAllReaded(obj) {
    allReaded = obj
}
function clearData() {
    allData = [];               // 所有数据
    allFilData = [];
    subscribeFilData = []
    focusData = [];             // 关注股票的数据
    followData = [];            // 自选的股票数据
    allReaded = {}              // 已读

    updatePopPage();
    updateUnread();
}
// 初始化配置
InitSetting();


function toStockDetail(stockObj) {
    var url = "", tradeLoc = "";
    switch (stockType) {
        case "dongcai":
            tradeLoc = (stockObj.m === 0) ? 'sz' : 'sh';
            url = `http://quote.eastmoney.com/${tradeLoc + stockObj.c}.html`;
            // url = "http://quote.eastmoney.com/"+tradeLoc + stockObj.c+".html";
            break;
        case "xueqiu":
            tradeLoc = (stockObj.m === 0) ? 'SZ' : 'SH';
            url = `https://xueqiu.com/S/${tradeLoc + stockObj.c}`;
            // url = "https://xueqiu.com/S/"+tradeLoc + stockObj.c;
            break;
        default:
            tradeLoc = (stockObj.m === 0) ? 'SZ' : 'SH';
            url = `https://xueqiu.com/S/${tradeLoc + stockObj.c}`;
            // url = "https://xueqiu.com/S/"+tradeLoc + stockObj.c;
            break;
    }
    if (url) { chrome.tabs.create({ url: url }); }
}



function getItemkey(item) {
    return item.t + '_' + item.tm + '_' + item.c;
}
function updateAllList(arr) {
    // 网络异常时,这里的 arr 是 false
    if (!arr) return [];
    var dealArr = arr
    var hasNotSecTech = true;       // 没有科创板
    // console.log("updateAllList hasNotSecTech before", dealArr)
    if (hasNotSecTech) {
        dealArr = dealArr.filter(item => !(/^688/).test(item.c))
    }
    // console.log("updateAllList arr", arr, allData)
    // console.log("updateAllList allData",allData)
    if (allData.length > 0) {
        var current = allData[0];
        var t = current.t, tm = current.tm, c = current.c
        var arrCurrentIndex = null;
        for (let m = 0; m < dealArr.length; m++) {
            if (t == dealArr[m].t && tm == dealArr[m].tm && c == dealArr[m].c) {
                arrCurrentIndex = m
                break;
            }
        }
        if (arrCurrentIndex) {
            allData.unshift(...arr.slice(0, arrCurrentIndex))
        }
        // console.log("arr allData new", allData )
        return allData;
    }
    console.log("updateAllList dealArr", dealArr)
    return dealArr
}
// 更新或初始化popup页面
function updatePopPage() {
    var views = chrome.extension.getViews({ type: 'popup' });
    if (views.length > 0) {
        var popPage = views[0];
        popPage.dataRendList();
        popPage.focusRendList();
        console.log(views[0]);
    }

}
/**
 * jsonp回调返回数据
 * @param {*} res 
 */
function jQuery35102755143189102953_1650598496290(res) {
    console.log("jsonp data", res)
    var resData = res.data;
    var allstock = (resData && resData.allstock) ? resData.allstock : [];
    return allstock
}

// 调用后台JS
function updateData() {
    var pomiseArr = [
        bgGetUnusualList({
            url: "http://push2ex.eastmoney.com/getAllStockChanges?type=8201,8202,8193,4,32,64,8207,8209,8211,8213,8215,8204,8203,8194,8,16,128,8208,8210,8212,8214,8216&cb=jQuery35102755143189102953_1650598496290&ut=7eea3edcaed734bea9cbfc24409ed989&dpt=wzchanges&_=1650598496311&pageindex=0&pagesize=1000",
            dataType: "jsonp",                                  //指定服务器返回的数据类型
            jsonp: "jQuery35102755143189102953_1650598496290"
        }, function (res) {
            console.log('bgGetUnusualList res', res);
            return eval(res)
        })
    ]
    // 有数据
    if (censusData[moment().format('YYYYMMDD')]) {
        pomiseArr.push(
            new Promise(function (resolve, reject) {
                resolve(censusData)
            })
        )
    } else {
        pomiseArr.push(getCensusData())
    }
    Promise.all(pomiseArr).then(function (resArr) {
        // console.log(" pomiseArr all",resArr)
        var censusObj = resArr[1][moment().format('YYYYMMDD')]
        allData = updateAllList(resArr[0]);
        allData.forEach(function (item) {
            // debugger
            // console.log( item.c , censusObj[item.c] )
            if (!item.caculated) {
                var d20 = (censusObj[item.c] && censusObj[item.c].d20) ? censusObj[item.c].d20 : '';
                var g20 = (censusObj[item.c] && censusObj[item.c].g20) ? censusObj[item.c].g20 : '';
                item.d20 = d20
                item.g20 = g20
                item.low20Rise = (d20) ? parseFloat((d20 * 1.2).toFixed(2)) : '';
                item.maxRise = (d20 && g20) ? parseFloat(((g20 / d20 - 1) * 100).toFixed(2)) : '';
                item.caculated = true;  // 表示已经计算过
            }

        })
        // console.log("PromiseallData",allData)
        allFilData = allData.filter(item => allDatafiltTypes.indexOf(item.t) > -1);
        console.log("allFilData", allFilData)
        console.log("inheritAllfil subscribeFilter", subscribeFilter)
        var inheritAllfil = subscribeFilter.inheritAllfil, maxRise20Days = parseFloat(subscribeFilter.maxRise20Days),
            LPrice20Days = parseFloat(subscribeFilter.LPrice20Days), HPrice20Days = parseFloat(subscribeFilter.HPrice20Days);
        var subscribeOriData = (inheritAllfil) ? allFilData : allData;
        subscribeFilData = subscribeOriData.filter(function (item) {
            if (maxRise20Days && maxRise20Days > 0 && item.maxRise > maxRise20Days) {
                return false
            }
            if (LPrice20Days && LPrice20Days > 0 && item.d20 < LPrice20Days) {
                return false
            }
            if (HPrice20Days && HPrice20Days > 0 && item.g20 > HPrice20Days) {
                return false
            }
            return true
        })
        console.log("subscribeFilData", subscribeFilData)
        focusData = allData.filter(item => focusCodeArr.indexOf(item.c) > -1).map(function (item) {
            var nItem = JSON.parse(JSON.stringify(item))
            nItem.readed = allReaded[getItemkey(item)] ? true : false;
            return nItem
        })
        followData = focusData.filter(item => followCodeArr.indexOf(item.c) > -1).map(function (item) {
            var nItem = JSON.parse(JSON.stringify(item))
            if (nItem.readed) {
                delete nItem.readed
            }
            return nItem
        })
        updatePopPage();
        updateUnread();
    })
}
function getCensusData() {
    return bgGetUnusualList({
        url: "https://ig507.com/data/all/jdgd?licence=6B9DEA84-49B8-D002-FC72-E8A87F153918",
    }, function (res) {
        // console.log('getCensusData res ori',eval( res ));
        var arr = {}
        var censusArr = eval(res);
        censusArr.forEach(function (item) {
            arr[item.dm.replace(/(sz|sh)/g, "")] = {
                d20: item.d20,
                g20: item.g20
            }
        })
        console.log('getCensusData res', censusArr, arr, moment().format('YYYYMMDD'));
        censusData[moment().format('YYYYMMDD')] = arr
        return censusData;
    });
}
// 推送消息数量
function emitMessageNum(number, color = [138, 120, 180, 255]) {
    console.log("emitMessageNum", chrome, number)
    chrome.browserAction.setBadgeBackgroundColor({ "color": color })
    chrome.browserAction.setBadgeText({
        "text": number ? number.toString() : ''
    });
    // if( number ){
    //     chrome.browserAction.setBadgeText({
    //         "text": number.toString()
    //     });
    // }

}

// 更新未读数量
function updateUnread() {
    emitMessageNum(focusData.filter(function (item) {
        return !item.readed
    }).length)
}

// unusualTaskDestroyed 任务结束后
function afterUnusualTaskDestroyed() {
    intervalTask(1)
}
// 设置 alarm task
function intervalTask(days = 0) {
    var setDay = moment().add(days, "days")
    var dayInWeek = setDay.day();
    if (dayInWeek >= 1 && dayInWeek <= 5) {
        // 可能是开盘日, 创建alarms事件,设定下一次启动时间
        chrome.alarms.create("unusualTask", {
            when: parseInt(setDay.set('hour', 9).set('minute', 25).format("x")) // x 表示毫秒
        });
        chrome.alarms.create("unusualTaskDestroyed", {
            when: parseInt(setDay.set('hour', 15).set('minute', 25).format("x")) // x 表示毫秒
        });
    } else {
        // 不可能是开盘日, 创建alarms事件,设定下一次启动时间
        // moment().day(8); // 下个星期日 ( 1 + 7 )
        chrome.alarms.create("unusualTask", {
            when: parseInt(moment().day(8).set('hour', 9).set('minute', 25).format("x")) // x 表示毫秒
        });
        chrome.alarms.create("unusualTaskDestroyed", {
            when: parseInt(moment().day(8).set('hour', 15).set('minute', 25).format("x")) // x 表示毫秒
        });
    }

}

// console.log( "chrome",chrome,chrome.alarms )
var unusualInterval = undefined
function restartInterval() {
    if (unusualInterval) {
        clearInterval(unusualInterval)
    }
    clearData()
    setInterval(updateData, 30 * 1000)
    updateData()
}
// 监听事件，所有事件响应都会在这里触发，只需设置一次
chrome.alarms.onAlarm.addListener(function (alarmInfo) {
    console.log("moment alarmInfo", alarmInfo);
    // setInterval(updateData,30*1000)
    if (alarmInfo.name == "unusualTask") {
        restartInterval();
        // console.log('当前时间：' + moment() );
        // console.log('本次周期时间：' + moment().format() );
    } else if (alarmInfo.name == "unusualTaskDestroyed") {
        if (unusualInterval) { clearInterval(unusualInterval) }
        afterUnusualTaskDestroyed()
    } else {

    }
})

console.log("moment", moment().add(6, "days").day())
console.log("moment", moment(), moment().add(30, 'seconds'), moment().add(30, 'seconds').format("X"))
intervalTask()

getCensusData();